package Neo4j

import (
	"BackEnd/common/Python"
	"fmt"
	"github.com/neo4j/neo4j-go-driver/v5/neo4j"
	"strings"
)

// CreateDriver 启动数据库驱动
func CreateDriver() (neo4j.Driver, error) {
	return neo4j.NewDriver(url, neo4j.BasicAuth(username, password, ""))
}

// CloseDriver 关闭数据库驱动
func CloseDriver(driver neo4j.Driver) error {
	return driver.Close()
}

func Query(cypher string) (error, Python.GraphData) {
	// 创建驱动
	driver, err := CreateDriver()
	if err != nil {
		return fmt.Errorf("create driver failed: %v", err), Python.GraphData{}
	}
	defer CloseDriver(driver)

	// 创建会话
	session := driver.NewSession(neo4j.SessionConfig{})
	defer session.Close()

	// 进行查询
	result, err := session.Run(cypher, nil)
	if err != nil {
		return fmt.Errorf("query failed: %v", err), Python.GraphData{}
	}

	graphData := &Python.GraphData{
		Nodes: make([]Python.Node, 0),
		Edges: make([]Python.Edge, 0),
	}

	nodeMap := make(map[int64]Python.Node) // 用于节点去重
	edgeMap := make(map[int64]Python.Edge) // 用于关系去重

	for result.Next() {
		record := result.Record()
		// fmt.Println(record.AsMap())

		// 处理节点
		if nodeValue, found := record.Get("n1"); found {
			if node, ok := nodeValue.(neo4j.Node); ok {
				processNode(node, graphData, nodeMap)
			}
		}
		if nodeValue, found := record.Get("n2"); found {
			if node, ok := nodeValue.(neo4j.Node); ok {
				processNode(node, graphData, nodeMap)
			}
		}

		// 处理关系
		if relValue, found := record.Get("r"); found {
			if rel, ok := relValue.(neo4j.Relationship); ok {
				processRelationship(rel, graphData, edgeMap)
			}
		}
	}
	if err := result.Err(); err != nil {
		return fmt.Errorf("result processing error: %v", err), Python.GraphData{}
	}
	fmt.Println("Node:", graphData.Nodes)
	fmt.Println("edge:", graphData.Edges)

	return nil, *graphData
}

// 辅助函数：处理单个节点
func processNode(node neo4j.Node, graphData *Python.GraphData, nodeMap map[int64]Python.Node) {
	if _, exists := nodeMap[node.Id]; exists {
		return
	}

	name := ""
	if nameVal, exists := node.Props["name"]; exists {
		if nameStr, ok := nameVal.(string); ok {
			name = nameStr
		}
	}

	newNode := Python.Node{
		ID:    Python.NodeID(node.Id),
		Label: name,
		Type:  strings.Join(node.Labels, ","),
	}

	nodeMap[node.Id] = newNode
	graphData.Nodes = append(graphData.Nodes, newNode)
}

// 辅助函数：处理单个关系
func processRelationship(rel neo4j.Relationship, graphData *Python.GraphData, edgeMap map[int64]Python.Edge) {
	if _, exists := edgeMap[rel.Id]; exists {
		return
	}

	newEdge := Python.Edge{
		ID:     Python.EdgeID(rel.Id),
		Source: Python.NodeID(rel.StartId),
		Target: Python.NodeID(rel.EndId),
		Label:  rel.Type,
	}

	edgeMap[rel.Id] = newEdge
	graphData.Edges = append(graphData.Edges, newEdge)
}

/*// 辅助函数：处理路径(包含多个节点和关系)
func processPath(path neo4j.Path, graphData *Python.GraphData, nodeMap map[int64]Python.Node, edgeMap map[int64]Python.Edge) {
	for _, node := range path.Nodes {
		processNode(node, graphData, nodeMap)
	}
	for _, rel := range path.Relationships {
		processRelationship(rel, graphData, edgeMap)
	}
}*/
